<template>
  <div class="login">
    <div class="login-box">
      <div class="title" ondragstart="return false" onselectstart="return false">
        <img src="../assets/img/login-logo.png" alt=""/>
      </div>

      <template>
        <!-- 登录 -->
        <el-form v-if="isLoginMode" :model="form" :rules="loginRules" class="form" ref="form">
          <el-alert
              :title="errorAlertText"
              v-if="errorAlert"
              @close="showErrorAlert(false)"
              class="error-alert"
              type="error"
              effect="dark">
          </el-alert>

          <el-form-item prop="lUserName" key="lUserName">
            <el-input
                v-model="form.lUserName"
                placeholder="用户名"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-form-item prop="lPassword" key="lPassword">
            <el-input
                type="password"
                v-model="form.lPassword"
                placeholder="密码"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-button class="button" @click="login" :disabled="requesting">登录</el-button>

          <div class="register"
               @click="changeMode"
               ondragstart="return false"
               onselectstart="return false">
            没有账号？立即注册
          </div>
        </el-form>

        <!-- 注册 -->
        <el-form v-else :model="form" :rules="registerRules" class="form" ref="form">
          <el-alert
              :title="errorAlertText"
              v-if="errorAlert"
              @close="showErrorAlert(false)"
              class="error-alert"
              type="error"
              effect="dark">
          </el-alert>

          <span class="info">基本信息</span>
          <el-form-item prop="rName" key="rName">
            <el-input
                v-model="form.rName"
                placeholder="姓名"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-form-item prop="rPhone" key="rPhone">
            <el-input
                v-model.number="form.rPhone"
                placeholder="手机号"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-form-item prop="rIdCard" key="rIdCard">
            <el-input
                v-model="form.rIdCard"
                placeholder="身份证号"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <span class="info">登录信息</span>

          <el-form-item prop="rUserName" key="rUserName">
            <el-input
                v-model="form.rUserName"
                placeholder="用户名"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-form-item prop="rPassword" key="rPassword">
            <el-input
                type="password"
                v-model="form.rPassword"
                placeholder="密码"
                @focus="showErrorAlert(false)">
            </el-input>
          </el-form-item>

          <el-button value="注册" class="button" @click="register" :disabled="requesting">注册</el-button>

          <div class="register"
               @click="changeMode"
               ondragstart="return false"
               onselectstart="return false">
            返回登录
          </div>
        </el-form>
      </template>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie';
import {base64encode} from 'crypto.js';
import modelUser from "../models/user";
//import {getUserData} from '@/model/user';

export default {
  name: "Login",
  data() {
    return {
      // 模式 登录 注册
      isLoginMode: true,
      // 登录失败
      errorAlert: false,
      // 登陆失败提示
      errorAlertText: '',
      // 请求中
      requesting: false,

      // 数据
      form: {},

      // 登录校验规则
      loginRules: {
        lUserName: this.$store.state.formRule.userName,
        //lPassword: this.$store.state.formRule.password
      },

      // 注册校验规则
      registerRules: {
        rName: this.$store.state.formRule.name,
        rPhone: this.$store.state.formRule.phone,
        rIdCard: this.$store.state.formRule.idCard,
        rUserName: this.$store.state.formRule.userName,
        rPassword: this.$store.state.formRule.password,
      },
    }
  },
  methods: {
    /**
     * 登录
     */
    login() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.handleLogin();
        }
        // 错误
        else {
          return false;
        }
      });
    },

    /**
     * 处理登录
     */
    handleLogin() {
      this.requesting = true;
      const usm = this.form.lUserName;
      const pwd = this.form.lPassword;

      const url = this.$store.state.api + `/Login/Login?userName=${usm}&password=${pwd}`;
      this.axios.get(url)
          .then((response) => {
            if (response.data.code == 200) {
              this.$message({
                type: response.data.data != null ? 'success' : 'error',
                message: response.data.data != null ? '登录成功！' : '登录失败！'
              });
              // 密码错误
              if (response.data.data == null) this.showErrorAlert(true, '账号或密码错误！');
              // 跳转
              else this.jump(usm, pwd);
            }
            this.requesting = false;
          })
          .catch((error) => {
            this.requesting = false;
            console.log(error);
          })
    },

    /**
     * 跳转
     */
    jump(usm, pwd) {
      const token = base64encode(usm) + '+' + base64encode(pwd);
      Cookies.set('token', token, {expires: 2});
      modelUser.loginGetUserData(token, true)
          .then(() => {
            // 获取参数（未登录时想访问的路由）
            let url = this.$route.query.redirect;
            url = url || "/";
            // 切换路由
            this.$router.push(url);
          });
    },

    /**
     * 注册
     */
    register() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.handleRegister();
        }
        // 错误
        else {
          return false;
        }
      });
    },

    /**
     * 处理注册
     */
    handleRegister() {
      this.requesting = true;

      // 生日
      /*const birthday = this.form.rIdCard.substring(6, 10) + "-"
          + this.form.rIdCard.substring(10, 12) + "-"
          + this.form.rIdCard.substring(12, 14);*/

      this.axios.post(this.$store.state.api + '/user/add', {
        //birthday: birthday,
        info: this.form.rIdCard,
        password: this.form.rPassword,
        phone: this.form.rPhone,
        // 默认用户
        role: '0',
        tuserName: this.form.rName,
        userName: this.form.rUserName
      }).then((response) => {
        if (response.data.code == 200) {
          this.$message({
            type: 'success',
            message: '注册成功，返回登录！'
          });
          this.changeMode();
        }
        this.requesting = false;
      }).catch((error) => {
        this.requesting = false;
        console.log(error);
      });
    },

    /**
     * 显示错误
     */
    showErrorAlert(isError, text = '') {
      this.errorAlert = isError;
      this.errorAlertText = text;
    },

    /**
     * 切换模式
     */
    changeMode() {
      this.showErrorAlert(false);
      this.form = {};
      this.isLoginMode = !this.isLoginMode;
    }
  }
};
</script>

<style lang="less" scoped>
@import "../assets/less/base.less";

.login {
  position: fixed;
  width: 100%;
  height: 100%;
  background: url(../assets/img/login-bg.png) center;
  background-size: cover;

  .login-box {
    width: 320px;
    position: fixed;
    right: 15%;
    top: 50%;
    transform: translateY(-50%);
    background: #f0edff;
    border-radius: 5px;
    padding: 30px 10px 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .error-alert {
      margin-bottom: 12px;
    }

    .title {
      width: 260px;
      margin: 0 auto 20px;

      img {
        width: 100%;
      }
    }

    .form {
      padding: 0 20px;
      width: 80%;
    }

    .button {
      height: 45px;
      border-radius: 5px;
      background: @yellowColor;
      color: white;
      cursor: pointer;
      width: 100%;
      margin-top: 20px;

      &:hover {
        background: @lightYellowColor;
      }
    }

    .register {
      cursor: pointer;
      margin-top: 12px;
      text-align: center;
    }

    .info {
      display: block;
      font-size: 14px;
      margin-bottom: 6px;
    }
  }
}
</style>